package com.hd.manager.shiro.token;

import com.hd.appcommon.constant.PrivilegeConstant;
import com.hd.appcommon.entity.Privilege;
import com.hd.appcommon.entity.Role;
import com.hd.appcommon.entity.Teacher;
import com.hd.appcommon.entity.User;
import com.hd.appcommon.service.IPrivilegeService;
import com.hd.appcommon.service.IRoleService;
//import com.hd.appcommon.service.TeacherService;
import com.hd.appcommon.service.TeacherService;
import com.hd.appcommon.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2018/8/24.
 * Description : token信息的辅助工具
 */
@Component
public class TokenCache {
    @Autowired
    private IPrivilegeService privilegeService;

    @Autowired
    private IRoleService roleService;
    //    @Autowired
//    private ILocationService locationService;
    @Autowired
    private UserService userService;


    public User getOrgMemberById(String teacherId) {
        return userService.getById(teacherId);
    }

    public List<Role> listRolesById(Integer teacherId) {
        return roleService.listByOrgMemberId(String.valueOf(teacherId));
    }

    //权限信息
    public List<Privilege> listPrivilegesById(Integer teacherId) {
        List<Privilege> privileges = listRolesById(teacherId)
                .stream()
                .flatMap(role ->
                        privilegeService.listByRoleId(role.getRoleId()).stream())
                .collect(Collectors.toList());
        List<String> idList = privileges.stream()
                .flatMap(p -> getValidIds(p.getPrivilegeId()).stream())
                .distinct()
                .collect(Collectors.toList());
        //去缓存中获取
        return PrivilegeCache.getByList(idList);
    }

    public List<String> getValidIds(String privilegeId) {
        String[] split = privilegeId.split(PrivilegeConstant.CONN_CHAR);
        LinkedList<String> result = new LinkedList<>();
        for (Integer i = 0; i < split.length; i++) {
            StringBuilder builder = new StringBuilder();
            boolean first = true;
            for (int j = 0; j < i + 1; j++) {
                if (first) {
                    first = false;
                } else {
                    builder.append(PrivilegeConstant.CONN_CHAR);
                }
                builder.append(split[j]);
            }
            result.add(builder.toString());
        }
        return result;
    }


}
